package jp.hamachi.android.demo.lock;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.OnKeyguardExitResult;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class LockActivity extends Activity implements OnClickListener, OnCheckedChangeListener, OnKeyguardExitResult {
    private static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
    private static final int REQUEST_PICK_APPWIDGET = 1;
    private static final int REQUEST_CREATE_APPWIDGET = 2;
    private static final int APPWIDGET_HOST_ID = 0x100;
    private AppWidgetHost mAppWidgetHost;
    private AppWidgetManager mAppWidgetManager;
    private View mLockView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAppWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
        mAppWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
        mAppWidgetHost.startListening();

        // レイアウトの設定
        setContentView(R.layout.main_activity);

        // ボタンクリック時のリスナーを設定
        findViewById(R.id.button_lock).setOnClickListener(this);

        // チェックボックス
        CheckBox check = (CheckBox) findViewById(R.id.check_isenabled);
        // 設定値を反映
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        check.setChecked(sp.getBoolean("is_enabled", false));
        // チェック状態変更時のリスナーを設定
        check.setOnCheckedChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_lock:
            // テストボタン押下時、ロック処理を呼ぶ
            addWidget();
            break;
        case R.id.button_unlock:
            // 解除ボタン押下時、解除処理を呼ぶ
            if (mLockView != null) {
                getWindowManager().removeView(mLockView);
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        KeyguardManager mKeyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        mKeyguard.exitKeyguardSecurely(this);
        KeyguardManager.KeyguardLock mLock = mKeyguard.newKeyguardLock("LockUtil");

        // チェック状態が変更された場合、プリファレンスに保存
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        Editor e = sp.edit();
        e.putBoolean("is_enabled", isChecked);
        e.commit();

        if (isChecked) {
            mLock.disableKeyguard();
        } else {
            mLock.reenableKeyguard();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case REQUEST_PICK_APPWIDGET:
                addAppWidget(data);
                break;
            case REQUEST_CREATE_APPWIDGET:
                completeAddAppWidget(data);
                break;
            }
        }
    }
    /**
     * 添加widget
     * @param data
     */
    @SuppressWarnings("deprecation")
    private void completeAddAppWidget(Intent data) {
        Bundle extras = data.getExtras();
        int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

        Log.d("completeAddAppWidget", "dumping extras content=" + extras.toString());
        Log.d("completeAddAppWidget", "appWidgetId:" + appWidgetId);
        AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);

        View hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);

        //layout.addInScreen(hostView, appWidgetInfo.minWidth, appWidgetInfo.minHeight);

        // 全画面
        //        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        //        params.width = LayoutParams.WRAP_CONTENT;
        //        params.height = LayoutParams.WRAP_CONTENT;
        //        params.type = LayoutParams.TYPE_SYSTEM_ALERT;
        //        params.format = PixelFormat.TRANSLUCENT;
        //        params.flags = LayoutParams.FLAG_DIM_BEHIND;

        //        LockUtil.getInstance().lock(this);

        //        ((ViewGroup)findViewById(R.id.root)).addView(hostView);

        // 設定値を取得
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isEnabled = sp.getBoolean("is_enabled", false);

        if (isEnabled) {
            // ロック有効の場合

            // ロック画面を作って
            mLockView = LayoutInflater.from(this).inflate(R.layout.lock, null);
            // ボタン押下時のリスナーを設定
            mLockView.findViewById(R.id.button_unlock).setOnClickListener(this);

            // android.view.WindowManager.LayoutParams
            // ロック画面表示用のパラメータ
            LayoutParams params = new LayoutParams();

            // 全画面
            params.width = LayoutParams.MATCH_PARENT;
            params.height = LayoutParams.MATCH_PARENT;
            // SystemAlert
            params.type = LayoutParams.TYPE_SYSTEM_ALERT;

            // 透過
            params.format = PixelFormat.TRANSLUCENT;
            // 裏はぼやける
            params.flags = LayoutParams.FLAG_BLUR_BEHIND;

            //********************
            params.format = PixelFormat.TRANSLUCENT;
//            params.systemUiVisibility = View.STATUS_BAR_HIDDEN;
            params.type = LayoutParams.TYPE_SYSTEM_ALERT;
            params.flags = LayoutParams.FLAG_BLUR_BEHIND;
            //******************

            // WindowManagerに追加
            ((ViewGroup) mLockView).addView(hostView);
            getWindowManager().addView(mLockView, params);
        } else {
            // ロックが無効
        }

    }

    /**
     * 選中了某個widget之後，根據是否有配置來決定直接添加還是彈出配置activity
     * @param data
     */
    private void addAppWidget(Intent data) {
        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

        String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
        Log.d("addAppWidget", "data:" + customWidget);
        if ("search_widget".equals(customWidget)) {
            //這裡直接將search_widget刪掉了  
            mAppWidgetHost.deleteAppWidgetId(appWidgetId);
        } else {
            AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);

            Log.d("addAppWidget", "configure:" + appWidget.configure);
            if (appWidget.configure != null) {
                //有配置，彈出配置  
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
                intent.setComponent(appWidget.configure);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

                startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
            } else {
                //沒有配置，直接添加  
                onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
            }
        }
    }
    /**
     * 請求添加一個新的widget
     */
    private void addWidget() {
        int appWidgetId = mAppWidgetHost.allocateAppWidgetId();

        Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
        pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        // add the search widget  
        ArrayList<AppWidgetProviderInfo> customInfo = new ArrayList<AppWidgetProviderInfo>();
        AppWidgetProviderInfo info = new AppWidgetProviderInfo();
        info.provider = new ComponentName(getPackageName(), "XXX.YYY");
        info.label = "Search";
        info.icon = R.drawable.icon;
        customInfo.add(info);
        pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
        ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
        Bundle b = new Bundle();
        b.putString(EXTRA_CUSTOM_WIDGET, "search_widget");
        customExtras.add(b);
        pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
        // start the pick activity  
        startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
    }

    @Override
    public void onKeyguardExitResult(boolean ret) {
        Log.d("TAG", "onKeyguardExitResult()" + ret);
    }
}
